﻿
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


using CMN.BLL;
using CMN.Common;
using CMN.Entity;
using CMN.Cache;
using CMN.Config;
namespace CMN.Framework
{
    /// <summary>
    /// 登陆类
    /// </summary>
    public class UserLogin
    {
        /// <summary>
        /// 登陆验证
        /// </summary>
        /// <param name="LoginName">用户名</param>
        /// <param name="LoginPassWord">密码</param>
        /// <param name="userkey">用户登陆标识</param>
        /// <returns>true/false</returns>
        public bool CheckLogin(string LoginName, string LoginPassWord, string userkey)
        {
            bool bBool = false;

            QueryParam qp = new QueryParam();
            qp.Where = string.Format("  U_StatUs=1 and  U_LoginName='{0}' and U_Password='{1}'", Utils.inSQL(LoginName), Utils.Md5(string.Concat(Utils.GetMD5Prefix,LoginPassWord), 32));
            int iInt = 0;
            BLLHelper bll = new BLLHelper();
            List<Sys_UserEntity> lst =bll.Sys_UserList(qp, out iInt);
            if (iInt > 0)
            {
                bBool = true;
                Sys_UserEntity sUT = (Sys_UserEntity)lst[0];
                string[] U_ExtendFieldArray = (sUT.U_ExtendField + "").Split(',');
                if (U_ExtendFieldArray.Length == 3)
                {
                 
                }
                checkOnline(sUT.U_LoginName.ToLower(), sUT.U_Password, Utils.GetSessionID, userkey);
                Signin(sUT);
               
            }
            return bBool;
        }
        /// <summary>
        /// 登陆验证
        /// </summary>
        /// <param name="LoginName">用户名</param>
        /// <param name="LoginPassWord">明文密码</param>
        /// <param name="userkey">用户登陆标识</param>
        /// <returns>true/false</returns>
        public bool CheckLogin(string LoginName, string LoginPassWord, string userkey, int i)
        {
            bool bBool = false;

            QueryParam qp = new QueryParam();
            qp.Where = string.Format("  U_StatUs=1 and  U_LoginName='{0}' and U_Password='{1}'", Utils.inSQL(LoginName), Utils.inSQL(LoginPassWord));
            int iInt = 0;
            BLLHelper bll = new BLLHelper();
            List<Sys_UserEntity> lst =bll.Sys_UserList(qp, out iInt);
            if (iInt > 0)
            {
                bBool = true;
                Sys_UserEntity sUT = (Sys_UserEntity)lst[0];
                string[] U_ExtendFieldArray = (sUT.U_ExtendField + "").Split(',');
                if (U_ExtendFieldArray.Length == 3)
                {
                  
                }
                checkOnline(sUT.U_LoginName.ToLower(), sUT.U_Password, Utils.GetSessionID, userkey);
                Signin(sUT);
               
            }
            return bBool;
        }


        /// <summary>
        /// 用户登陆
        /// </summary>
        /// <param name="sUT">用户实体类</param>
        private void Signin(Sys_UserEntity sUT)
        {

            System.Web.Security.FormsAuthenticationTicket tk = new FormsAuthenticationTicket(1,
                    sUT.UserID.ToString(),
                    DateTime.Now,
                    DateTime.Now.AddMinutes(OnlineConfigs.GetConfig().OnlineMinute),
                    true,
                    "",
                    System.Web.Security.FormsAuthentication.FormsCookiePath
                    );

            string key = System.Web.Security.FormsAuthentication.Encrypt(tk); //得到加密后的身份验证票字串 

            HttpCookie ck = new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, key);
            //ck.Domain = System.Web.Security.FormsAuthentication.CookieDomain;  // 这句话在部署网站后有用，此为关系到同一个域名下面的多个站点是否能共享Cookie
            HttpContext.Current.Response.Cookies.Add(ck);
            //string temp = System.Web.Security.FormsAuthentication.Decrypt(HttpContext.Current.Request.Cookies.Get(0).Value ).ToString();
            Sys_EventEntity sysEvent = new Sys_EventEntity();
            sysEvent.DataTable_Action = DataTableAction.Insert;
            sysEvent.E_DateTime = DateTime.Now;
            sysEvent.E_From = Utils.GetUrlReferrer();
            sysEvent.E_IP = Utils.GetIP();
            sysEvent.E_M_Action = "login";

            sysEvent.E_M_Name = "登录成功";

            sysEvent.E_Type = 1;
            sysEvent.E_UserID = Utils.GetUserID;
            sysEvent.E_U_LoginName = sUT.U_LoginName.ToLower();
            BLLHelper bll = new BLLHelper();
            bll.Sys_EventInsertUpdateDelete(sysEvent);

        }

        /// <summary>
        /// 检测在线用户表
        /// </summary>
        /// <param name="U_LoginName">用户名</param>
        /// <param name="U_Password">密码</param>
        /// <param name="SessionID">用户sessionID</param>
        /// <param name="userkey">用户Key</param>
        private void checkOnline(string U_LoginName, string U_Password, string SessionID, string userkey)
        {
            if (CMNOnline.Instance().OnlineCheck(U_LoginName))
            {
                HttpContext.Current.Session["CheckCode"] = Utils.RndNum(4);
                //OnlineUser<int> ou =  CMNPermission.UserOnlineList.GetValue(U_LoginName);
                OnlineUser<string> ou = CMNOnline.Instance().GetOnlineMember(U_LoginName);
                UserLogin.MoveErrorLoginUser(userkey);

            }
            else
            {
                CMNOnline.Instance().InsertOnlineUser(U_LoginName);

            }
        }

        /// <summary>
        /// 用户退出
        /// </summary>
        public static void UserOut()
        {
            try
            {
                //CMNPermission.UserOnlineList.Remove(Utils.GetUserID);
                //写退出日志
                // AppLog.Write("退出", AppLog.LogMessageType.Info);
                //退出操作
                Sys_EventEntity sysEvent = new Sys_EventEntity();
                sysEvent.DataTable_Action = DataTableAction.Insert;
                sysEvent.E_DateTime = DateTime.Now;
                sysEvent.E_From = Utils.GetUrlReferrer();
                sysEvent.E_IP = Utils.GetIP();
                sysEvent.E_M_Action = "logout";

                sysEvent.E_M_Name = "注销登陆";

                sysEvent.E_Type = 1;
                sysEvent.E_UserID = Utils.GetUserID;
                sysEvent.E_U_LoginName = UserData.GetUserData.U_LoginName;
                BLLHelper bll = new BLLHelper();
                bll.Sys_EventInsertUpdateDelete(sysEvent);
                CMNOnline.Instance().OnlineRemove(UserData.GetUserData.U_LoginName, Utils.GetSessionID);
                UserData.MoveUserPermissionCache(Utils.GetUserID);
                UserData.MoveUserCache(Utils.GetUserID);
                System.Web.Security.FormsAuthentication.SignOut();
            }
            catch (Exception ex)
            {
                
                System.Web.Security.FormsAuthentication.SignOut();
            }
        }

        #region "用户登陆出错次数检测"
        private static CacheOnline<string, LoginErrorUser> _LoginErrorList = new CacheOnline<string, LoginErrorUser>(6);

        /// <summary>
        /// 获得用户登陆出错次数
        /// </summary>
        public static int GetLoginUserError(string UserKey)
        {
            int errorcount = 0;
            LoginErrorUser LUser = _LoginErrorList.GetValue(UserKey);
            if (LUser != null)
            {
                errorcount = LUser.ErrorCount;
            }
            return errorcount;
        }

        /// <summary>
        /// 检测用户是否可以登陆
        /// </summary>
        /// <param name="UserKey">用户UserKey</param>
        /// <returns>true可以登陆,false不可登陆</returns>
        public static bool CheckDisableLoginUser(string UserKey)
        {
            bool rBool = false;
            LoginErrorUser LUser = _LoginErrorList.GetValue(UserKey);
            if (LUser == null)
            {
                LUser = new LoginErrorUser();
                LUser.U_Guid = UserKey;
                LUser.U_Type = true;
                LUser.ErrorCount = 1;
                LUser.U_Name = UserKey;
                _LoginErrorList.InsertUser(UserKey, LUser);
                rBool = true;
            }
            else
            {
                if (LUser.ErrorCount <6)
                {
                    LUser.ErrorCount++;
                    return true;
                }
                else
                {
                    _LoginErrorList.Access(UserKey);
                }
            }
            return rBool;
        }

        /// <summary>
        /// 移除登陆列表中用户
        /// </summary>
        /// <param name="UserKey">用户key</param>
        /// <returns>true成功,false失败</returns>
        public static bool MoveErrorLoginUser(string UserKey)
        {
            bool rBool = false;
            _LoginErrorList.Remove(UserKey);
            return rBool;
        }




        /// <summary>
        /// 用户登陆出错类
        /// </summary>
        public class LoginErrorUser : OnlineUser<string>
        {
            /// <summary>
            /// 用户登陆出错次数
            /// </summary>
            public int ErrorCount;
        }
        #endregion
    }
}
